#!/usr/bin/python3
#coding=utf-8

import datetime
import logging
import logging.handlers

info = logging.INFO
error = logging.ERROR
debug = logging.DEBUG
warn = logging.WARN

class CLog:
    def __init__(self, logName , isPrint = False):
        self.logFormat = "%(asctime)s %(levelname)s %(message)s"
        self.m_log = logging.getLogger('mylogger')
        self.m_log.setLevel(debug)
        self.isPrint = isPrint
        self.logHandler = logging.handlers.TimedRotatingFileHandler(filename=logName, when='midnight', interval=1, backupCount=7, atTime=datetime.time(0, 0, 0, 0))
        self.logHandler.setFormatter(logging.Formatter(self.logFormat))
        self.m_log.addHandler(self.logHandler)

        self.timeNow = datetime.datetime.now()
        self.level = "info"

    def log(self, s, level=info):
        if (level == info):
            self.m_log.info("   " + s)
            self.level = "info "
        if (level == error):
            self.m_log.error("  " + s)
            self.level = "error"

        if (level == warn):
            self.m_log.warning(s)
            self.level = "warn "

        if (level == debug):
            self.m_log.debug("  " + s)
            self.level = "debug"

        if(self.isPrint):
            self.timeNow = datetime.datetime.now()
            print(self.timeNow.strftime('%Y-%m-%d %H:%M:%S.%f ')[:-4], self.level.format("%s"), s)


#已测试
#timeNow = datetime.datetime.now()
#print(timeNow)
#timeStr = timeNow.strftime('%Y%m%d')
#print(timeStr)
#
#testLog = CLog("test_log_class_" + timeStr + ".log", True)
#
# while True:
#     testLog.log("test123344567788", debug)
#     testLog.log("test123344567788", info)
#     testLog.log("test123344567788", error)
#     testLog.log("test123344567788", warn)